package com.sean.community.actuator;

import com.sean.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

// 数据库监控端点
@Component
@Endpoint(id = "database")
public class DatabaseEndpoint {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseEndpoint.class);

    // 获取数据库连接
    // 连接池
    private DataSource dataSource;
    // 连接参数

    @Autowired
    public void setDataSource(@Qualifier("dataSource") DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @ReadOperation
    public String checkConnection(){
        try(
                Connection connection = dataSource.getConnection()
        ){
            return CommunityUtil.getJSONString(200, "数据库连接正常！");
        }catch (SQLException e){
            logger.error("数据库连接错误！" + e.getMessage());
            return CommunityUtil.getJSONString(500, "数据库连接异常！");
        }
    }
}
